package com.ge.boot03web.config;

import com.ge.boot03web.component.YamlHttpMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.CacheControl;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 自定义静态资源访问规则
 */

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //保留原有规则
        WebMvcConfigurer.super.addResourceHandlers(registry);

        //添加需要的规则，如设置访问路径、资源路径、缓存机制等
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/a/")
                .setCacheControl(CacheControl.maxAge(7200, TimeUnit.SECONDS));

    }

    /**
     * 增加一个能把对象转换为yaml的HttpMessageConverter
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new YamlHttpMessageConverter());
    }

    /*
    /**
     * 通过@Bean标签直接注入WebMvcConfigurer配置类
     *
    @Bean
    public WebMvcConfigurer webMvcConfigurer(){
        return new WebMvcConfigurer() {
            @Override
            public void addResourceHandlers(ResourceHandlerRegistry registry) {
                WebMvcConfigurer.super.addResourceHandlers(registry);
                registry.addResourceHandler("/static/**")
                        .addResourceLocations("classpath:/a/")
                        .setCacheControl(CacheControl.maxAge(7200, TimeUnit.SECONDS));
            }
        };
    }

     */
}
